package cn.edu.ujn.food.controller;

import cn.edu.ujn.food.entity.*;
import cn.edu.ujn.food.service.*;
import cn.edu.ujn.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@org.springframework.stereotype.Controller
public class ReviewController {
    @Autowired
    private UserService userService;
    @Autowired
    private RestaurantService restaurantService;
    @Autowired
    private ReviewService reviewService;
    @ModelAttribute("userMap")
    public Map<Integer, String> getUserMap() {
        List<User> users = userService.findAll();
        Map<Integer, String> userMap = new HashMap<>();
        for (User user : users) {
            userMap.put(user.getUserId(), user.getUserName());
        }
        return userMap;
    }

    @ModelAttribute("reverseUserMap")
    public Map<String, Integer> getReverseUserMap() {
        List<User> users = userService.findAll();
        Map<String, Integer> reverseUserMap = new HashMap<>();
        for (User user : users) {
            reverseUserMap.put(user.getUserName(), user.getUserId());
        }
        return reverseUserMap;
    }

    @ModelAttribute("restaurantMap")
    public Map<Integer, String> getRestaurantMap() {
        List<Restaurant> restaurants = restaurantService.findAll();
        Map<Integer, String> restaurantMap = new HashMap<>();
        for (Restaurant restaurant : restaurants) {
            restaurantMap.put(restaurant.getRestId(), restaurant.getRestName());
        }
        return restaurantMap;
    }

    @PutMapping("/review/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateReview(@PathVariable("id") Integer reviewId, @RequestBody Review review) {
        try {
            review.setReviewId(reviewId);
            reviewService.update(review);
            return ResponseEntity.ok(Map.of("success", true, "message", "评论信息已成功更新"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "更新失败: " + e.getMessage()));
        }
    }

    @DeleteMapping("/review/{id}")
    public ResponseEntity<Map<String, Object>> deleteReview(@PathVariable("id") Integer reviewId) {
        try {
            boolean isDeleted = reviewService.deleteById(reviewId);
            if (isDeleted) {
                return ResponseEntity.ok(Map.of("success", true, "message", "评论信息删除成功！"));
            } else {
                return new ResponseEntity<>(Map.of("success", false, "message", "评论信息删除失败，评论不存在或已删除。"), HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            return new ResponseEntity<>(Map.of("success", false, "message", "评论信息删除失败: " + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/review")
    @ResponseBody
    public String createReview(Review review) {
        try {
            reviewService.insert(review);
            return "OK";
        } catch (Exception e) {
            return "FAIL";
        }
    }

    @GetMapping("/review")
    public String listReview(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "row", defaultValue = "10") Integer rows, Model model, Review review, @RequestParam(value = "userName", required = false) String userName) {
        review.setStart((page - 1) * rows);
        review.setRows(rows);
        List<User> users = userService.findAll();
        Map<String, Integer> reverseUserMap = new HashMap<>();
        for (User user : users) {
            reverseUserMap.put(user.getUserName(), user.getUserId());
        }
        review.setUserId(reverseUserMap.get(userName));
        Page<Review> page10 = reviewService.selectAll(review);
        page10.setPage(page);
        model.addAttribute("page", page10);
        return "review";
    }

    @GetMapping("/review/{id}")
    @ResponseBody
    public ResponseEntity<Review> getReviewById(@PathVariable("id") Integer reviewId) {
        Review review = reviewService.queryById(reviewId);
        if (review == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(review, HttpStatus.OK);
    }
}


